#include "nc_cardlib.h"

unsigned int HexToStr(unsigned char *in, unsigned int insize, char *out)
{
	int j = 0;

	for(int i = 0;i < insize; i++ )
	{
		sprintf((char*)&out[j],"%02x",in[i]);
		j += 2;
	}
	return 0;
}
//  ASCII->HEX	  "123A5"-->0x12,0x3A,0x50
unsigned int StrToHex(char *in, unsigned int insize, unsigned char *out)
{
	for( int i = 0; i < insize; i++ )
	{ 
		if( ( in[i] <= '9' ) && ( in[i] >= '0' ) )
		{ 
			if( ( i % 2 ) == 0 )
			{
				out[i/2]   = ( in[i] - '0' );	
				out[i/2] <<= 4;
			}
			else
			{ out[i/2] |= ( in[i] - '0' ); }
		}
		else if( ( in[i] <= 'F' ) && ( in[i] >= 'A' ) )
		{
			if( ( i % 2 ) == 0 )
			{
				out[i/2]   = ( in[i] - 'A' ) + 0x0A;	
				out[i/2] <<= 4;
			}
			else
			{ out[i/2] |= ( in[i] - 'A' ) + 0x0A; }					
		}
		else if( ( in[i] <= 'f' ) && ( in[i] >= 'a' ) )
		{
			if( ( i % 2 ) == 0 )
			{
				out[i/2]   = ( in[i] - 'a' ) + 0x0A;	
				out[i/2] <<= 4;
			}
			else
			{ out[i/2] |= ( in[i] - 'a' ) + 0x0A; }					
		}
		else
		{ return 1; }
	}
	return 0;
}
unsigned int ICC_APDU_Exchange( unsigned int cid, unsigned char *in_data, unsigned int in_size, 
	                            unsigned char *out_data, unsigned int *out_size, unsigned int out_maxbuf )
{
    
	unsigned int len=0,rcode = 0;
	unsigned char buf[ICC_APUD_MAXBUF*2];
	
	memset(buf, 0, ICC_APUD_MAXBUF*2);
	if(cid == 1)//PSAM卡
	{
		printf("PSAM:\n");
		HexToStr( in_data, in_size, (char*)&buf[1] );
        buf[0] = 'P';
		rcode = Com_Dev_TxData1( buf, in_size*2+1, 0, 0 );
		if( rcode != 0 )
		{ DEF_SysCard_Debug; return rcode; }
	}
	else
	{
		HexToStr( in_data, in_size, (char*)buf );

		rcode = Com_Dev_TxData1( buf, in_size*2, 0, 0 );
		if( rcode != 0 )
		{ DEF_SysCard_Debug; return rcode; }
	}
	
	//接收命令
	memset(buf, 0, ICC_APUD_MAXBUF*2);
	rcode = Com_Dev_RxData1( buf, &len,  1024, 0, 0 ); 
	if( rcode != 0 )
	{ DEF_SysCard_Debug; return rcode; }
	
    StrToHex( (char*)buf, len, out_data );
    
    *out_size = len/2;
	return 0;
}

unsigned int ICC_PCD_RadioOff( void )
{
	return 0;
}